package com.example.libpro.MyActivity.adminActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.activity.EdgeToEdge;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.graphics.Insets;
import androidx.core.view.ViewCompat;
import androidx.core.view.WindowInsetsCompat;

import com.example.libpro.R;
import com.example.libpro.Service.BookService;
import com.example.libpro.Service.ReaderService;

public class AdminAddReaderActivity extends AppCompatActivity implements View.OnClickListener{
    private static final String TAG = "AdminAddReaderActivity";
    private ReaderService readerService;
    private boolean readerServiceBound;
    private EditText etName;
    private EditText etPhone;
    private EditText etPassword;
    private Button btnAddReader;
    private ServiceConnection connection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName className, IBinder service) {
            ReaderService.LocalBinder binder = (ReaderService.LocalBinder) service;
            readerService = binder.getService();
            readerServiceBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            readerServiceBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_admin_add_reader);

        Log.i(TAG, "onCreate: Activity 启动，开始绑定 readerService");
        Intent intent = new Intent(this, ReaderService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);

        etName=findViewById(R.id.etName);
        etPhone=findViewById(R.id.etPhone);
        etPassword=findViewById(R.id.etPassword);
        btnAddReader=findViewById(R.id.btnAddReader);
        btnAddReader.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        //判断绑定状态和各个控件的输入
        boolean isOk = readerServiceBound && !etName.getText().toString().isEmpty() && !etPhone.getText().toString().isEmpty() && !etPassword.getText().toString().isEmpty();
        if (isOk) {
            ReaderService.ServiceResult result = readerService.addReader(etName.getText().toString(), etPhone.getText().toString(), etPassword.getText().toString());
            if (result.isSuccess()) {
                Log.i(TAG, "onClick: 添加成功");
                finish();
            } else {
                Log.i(TAG, "onClick: 添加失败");
                Log.w(TAG, "onClick: " + result.getMessage());
            }
        }

    }
}